<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="false"
    :okAuth="'wh:pd:whPdStockBill:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #whPdStockBillsList>
        <BasicTable
          @register="registerWhPdStockBillsTable"
          :canResize="false"
          :showTableSetting="false"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsWhPdWhPdStockBillForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { WhPdStockBill, whPdStockBillSave, whPdStockBillForm, whPdStockBillsListData } from '/@/api/wms/wh/pd/whPdStockBill';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wh.pd.whPdStockBill');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<WhPdStockBill>({} as WhPdStockBill);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增wh_pd_stock_bill') : t('查看盘点单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('公司名称'),
      field: 'companyname',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('来源id'),
      field: 'sourceId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      show: false,
    },
    {
      label: t('单据号'),
      field: 'djno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
    },
    {
      label: t('来源单号'),
      field: 'sourceNo',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
    },
    {
      label: t('盘点方式'),
      field: 'pdType',
      component: 'Select',
      componentProps: {
        maxlength: 1,
        dictType: 'wms_pd_type',
      },
      required: true,
    },
    {
      label: t('单据状态'),
      field: 'status',
      component: 'Select',
      componentProps: {
        maxlength: 1,
        dictType: 'wms_pd_zf_status',
      },
      dynamicDisabled: true,
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      required: true,
    },
    {
      label: t('盘点状态'),
      field: 'pdStatus',
      component: 'Select',
      componentProps: {
        maxlength: 1,
        dictType: 'wms_pd_pdStatus',
      },
      required: true,
    },
    {
      label: t('任务总数'),
      field: 'iqty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('实盘总数'),
      field: 'sumqty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    // {
    //   label: t('仓库'),
    //   field: 'whcode',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 64,
    //   },
    // },
    {
      label: t('货位'),
      field: 'poscode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('盘点明细'),
      field: 'whPdStockBillsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'whPdStockBillsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 8, md: 24 },
  });

  const [registerWhPdStockBillsTable, whPdStockBillsTable] = useTable({
    api: whPdStockBillsListData, // 使用API获取数据
    beforeFetch: (params: any) => {
      // 设置查询参数为 djno.djno
      if (record.value && record.value.djno) {
        // 如果djno是对象，取其djno属性；如果是字符串，直接使用
        const djnoValue = (record.value.djno as any)?.djno || record.value.djno;
        params['djno.djno'] = djnoValue;
      }
      return params;
    },
    columns: [
      {
        title: t('物料编码'),
        dataIndex: 'basInv.viewCode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('物料名称'),
        dataIndex: 'basInv.invName',
        width: 300,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('形象刊'),
        dataIndex: 'freeVO.cfree1',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('货位'),
        dataIndex: 'basPosition.posName',
        width: 120,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('账存数'),
        dataIndex: 'iqty',
        width: 90,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        showSummary: true,
        showTotalSummary: true,
      },
      {
        title: t('实盘数'),
        dataIndex: 'frealqty',
        width: 90,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        showSummary: true,
        showTotalSummary: true,
      },
      {
        title: t('盈亏数'),
        dataIndex: 'fqty',
        width: 90,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        showSummary: true,
        showTotalSummary: true,
      },
      {
        title: t('盘盈亏状态'),
        dataIndex: 'pykStatus',
        // key: 'a.pyKstatus',
        dictType: 'wms_pd_yk_status',
        width: 130,
        align: 'left',
      },
      // {
      //   title: t('来源id'),
      //   dataIndex: 'sourceId',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: false,
      // },

      {
        title: t('来源单号'),
        dataIndex: 'sourceNo',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      // {
      //   title: t('来源明细ID'),
      //   dataIndex: 'sourceDid',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: false,
      // },
      {
        title: t('行备注'),
        dataIndex: 'remarks',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'InputTextArea',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      // {
      //   title: t('自由项1'),
      //   dataIndex: 'cfree1',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 255,
      //   },
      //   editRule: false,
      // },
      // {
      //   title: t('自由项2'),
      //   dataIndex: 'cfree2',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 255,
      //   },
      //   editRule: false,
      // },
      // {
      //   title: t('自由项3'),
      //   dataIndex: 'cfree3',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 255,
      //   },
      //   editRule: false,
      // },

      {
        title: t('盘点人'),
        dataIndex: 'pdByName',
        width: 130,
        align: 'left',
      },
      {
        title: t('盘点时间'),
        dataIndex: 'pdDate',
        width: 130,
        align: 'left',
      },
    ],
    // actionColumn: {
    //   width: 60,
    //   align: 'right', // 操作列右对齐
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'i-ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleWhPdStockBillsDelete.bind(this, record),
    //       },
    //       auth: 'wh:pd:whPdStockBill:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    // pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    immediate: true, // 立即加载
    showTotalCustomSummary: true,
    showCustomSummary: true,
  });

  async function setWhPdStockBillsTableData(_res: Recordable) {
    // 表格配置为立即加载，这里不需要手动调用reload
    // 数据会通过beforeFetch自动获取
    console.log('表格数据将通过API自动加载');
  }

  function handleWhPdStockBillsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleWhPdStockBillsAdd() {
    whPdStockBillsTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleWhPdStockBillsDelete(record: Recordable) {
    whPdStockBillsTable.deleteTableDataRecord(record);
  }

  // 手动刷新表格数据
  async function reloadWhPdStockBillsTable() {
    if (record.value && record.value.djno) {
      await whPdStockBillsTable.reload();
    }
  }

  async function getWhPdStockBillsList() {
    let whPdStockBillsListValid = true;
    let whPdStockBillsList: Recordable[] = [];
    for (const record of whPdStockBillsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        whPdStockBillsListValid = false;
      }
      whPdStockBillsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of whPdStockBillsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      whPdStockBillsList.push({
        ...record,
        status: '1',
      });
    }
    if (!whPdStockBillsListValid) {
      throw { errorFields: [{ name: ['whPdStockBillsList'] }] };
    }
    return whPdStockBillsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data: any) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await whPdStockBillForm(data);
    record.value = ((res as any).whPdStockBill || res || {}) as WhPdStockBill;
    (record.value as any).__t = new Date().getTime();
    setFieldsValue(record.value);

    // 设置表格数据（现在只是一个占位符函数）
    await setWhPdStockBillsTableData(res);

    setDrawerProps({ loading: false });

    // 延迟触发表格重新加载，确保record.value已经设置好
    setTimeout(() => {
      try {
        whPdStockBillsTable.reload();
      } catch (error) {
        console.warn('延迟重新加载表格失败:', error);
      }
    }, 500);
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: (record.value as any).isNewRecord,
        djno: record.value.djno,
      };
      data.whPdStockBillsList = await getWhPdStockBillsList();
      // console.log('submit', params, data, record);
      const res = await whPdStockBillSave(params, data);
      showMessage((res as any).message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
